import {
  Body,
  Controller,
  Get,
  Inject,
  Post,
  Provide,
  ALL,
} from '@midwayjs/decorator';
// import { AuthDTO } from '../dto/auth';
import { AuthService } from '../service/auth';
import { CaptchaService } from '@midwayjs/captcha'
// import { ApiResponse } from '@midwayjs/swagger';
import { LoginDTO } from '../dto/login'
import { BaseError as R } from '../../../common/base.error'
import { RSAService } from '../../../common/rsa.service'
import { Context } from '@midwayjs/core';
import { ResfreshTokenDTO } from '../dto/refreshToken';
import { NotLogin } from '../../../decorator/not.login';

@Provide()
@Controller('/auth')
export class AuthController {
  @Inject()
  authService: AuthService;

  @Inject()
  captchaService: CaptchaService

  @Inject()
  rasService: RSAService

  @Inject()
  ctx: Context

  @Post('/login')
  @NotLogin()
  // @ApiResponse({ type: AuthDTO })
  async login(@Body(ALL) data: LoginDTO) {
    const { captchaId, captcha } = data;
    
    // 验证码校验
    const captchChecked = await this.captchaService.check(captchaId, captcha);
    if (!captchChecked) {
      throw R.validateError('验证码错误')
    }

    return await this.authService.login(data);
  }

  @Get('/captcha')
  @NotLogin()
  async getImageCaptcha() {
    const { id, imageBase64 } = await this.captchaService.formula({
      height: 40,
      width: 120,
      noise: 1
    });

    return {
      id,
      imageBase64
    }
  }

  @Get("/publicKey")
  @NotLogin()
  async getPublicKey() {
    return await this.rasService.getPublicKey();
  }

  @Get("/current/user")
  async getCurrentUser() {
    console.log('22223', this.ctx);
    // return {}
    return await this.authService.getUserById(this.ctx.userinfo.userId);
  }

  @Post("/refresh/token", { description: '刷新token' })
  async refreshToken(@Body(ALL) data: ResfreshTokenDTO) {
    return this.authService.refreshToken(data)
  }
 }